/**
 * PromptTemplatePicker - 提示词模板选择器
 * 
 * 功能：
 * 1. 显示所有可用的提示词模板
 * 2. 支持按类别筛选
 * 3. 支持搜索
 * 4. 显示模板详情和使用统计
 */

import { useState, useMemo } from 'react';
import { Search, Star, TrendingUp, Sparkles, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { cn } from '@/lib/utils';
import type { PromptTemplate, PromptCategory } from '@/types/prompt';

// ============================================================================
// 类型定义
// ============================================================================

export interface PromptTemplatePickerProps {
  /** 模板列表 */
  templates: PromptTemplate[];
  /** 选择模板时的回调 */
  onSelect: (template: PromptTemplate) => void;
  /** 关闭选择器时的回调 */
  onClose?: () => void;
  /** 当前选中的模板ID */
  selectedId?: string;
  /** 自定义类名 */
  className?: string;
}

// 类别显示配置
const CATEGORY_CONFIG: Record<PromptCategory, { label: string; emoji: string; color: string }> = {
  code: { label: '代码', emoji: '💻', color: 'bg-blue-500/10 text-blue-500 border-blue-500/20' },
  writing: { label: '写作', emoji: '✍️', color: 'bg-purple-500/10 text-purple-500 border-purple-500/20' },
  analysis: { label: '分析', emoji: '📊', color: 'bg-green-500/10 text-green-500 border-green-500/20' },
  translation: { label: '翻译', emoji: '🌐', color: 'bg-yellow-500/10 text-yellow-500 border-yellow-500/20' },
  education: { label: '教育', emoji: '🎓', color: 'bg-pink-500/10 text-pink-500 border-pink-500/20' },
  business: { label: '商务', emoji: '💼', color: 'bg-orange-500/10 text-orange-500 border-orange-500/20' },
  creative: { label: '创意', emoji: '🎨', color: 'bg-violet-500/10 text-violet-500 border-violet-500/20' },
  research: { label: '研究', emoji: '🔬', color: 'bg-cyan-500/10 text-cyan-500 border-cyan-500/20' },
  other: { label: '其他', emoji: '📝', color: 'bg-gray-500/10 text-gray-500 border-gray-500/20' },
};

// ============================================================================
// 主组件
// ============================================================================

export function PromptTemplatePicker({
  templates,
  onSelect,
  onClose,
  selectedId,
  className,
}: PromptTemplatePickerProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<PromptCategory | 'all'>('all');

  // 获取所有类别及其模板数量
  const categories = useMemo(() => {
    const counts: Record<string, number> = {};
    templates.forEach(t => {
      counts[t.category] = (counts[t.category] || 0) + 1;
    });
    return counts;
  }, [templates]);

  // 过滤模板
  const filteredTemplates = useMemo(() => {
    return templates.filter(template => {
      // 类别筛选
      if (selectedCategory !== 'all' && template.category !== selectedCategory) {
        return false;
      }

      // 搜索筛选
      if (searchQuery) {
        const query = searchQuery.toLowerCase();
        return (
          template.name.toLowerCase().includes(query) ||
          template.description.toLowerCase().includes(query) ||
          template.tags?.some(tag => tag.toLowerCase().includes(query))
        );
      }

      return true;
    });
  }, [templates, selectedCategory, searchQuery]);

  // 排序：内置模板优先，然后按使用次数
  const sortedTemplates = useMemo(() => {
    return [...filteredTemplates].sort((a, b) => {
      // 内置模板优先
      if (a.isBuiltin && !b.isBuiltin) return -1;
      if (!a.isBuiltin && b.isBuiltin) return 1;
      
      // 按使用次数降序
      return (b.usageCount || 0) - (a.usageCount || 0);
    });
  }, [filteredTemplates]);

  return (
    <div className={cn('flex flex-col h-full', className)}>
      {/* 头部 */}
      <div className="flex items-center justify-between p-4 border-b">
        <div className="flex items-center gap-2">
          <Sparkles className="h-5 w-5 text-primary" />
          <h3 className="font-semibold">提示词模板</h3>
          <Badge variant="secondary" className="ml-2">
            {filteredTemplates.length} 个
          </Badge>
        </div>
        {onClose && (
          <Button variant="ghost" size="icon" onClick={onClose} className="h-8 w-8">
            <X className="h-4 w-4" />
          </Button>
        )}
      </div>

      {/* 搜索栏 */}
      <div className="p-4 border-b space-y-3">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="搜索模板..."
            className="pl-9"
          />
        </div>

        {/* 类别筛选 */}
        <div className="flex gap-2 flex-wrap">
          <Button
            variant={selectedCategory === 'all' ? 'default' : 'outline'}
            size="sm"
            onClick={() => setSelectedCategory('all')}
            className="h-8"
          >
            全部 ({templates.length})
          </Button>
          {Object.entries(CATEGORY_CONFIG).map(([category, config]) => {
            const count = categories[category] || 0;
            if (count === 0) return null;
            
            return (
              <Button
                key={category}
                variant={selectedCategory === category ? 'default' : 'outline'}
                size="sm"
                onClick={() => setSelectedCategory(category as PromptCategory)}
                className="h-8"
              >
                {config.emoji} {config.label} ({count})
              </Button>
            );
          })}
        </div>
      </div>

      {/* 模板列表 */}
      <ScrollArea className="flex-1 p-4">
        {sortedTemplates.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <Sparkles className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p>未找到匹配的模板</p>
            <p className="text-sm mt-2">尝试调整搜索条件</p>
          </div>
        ) : (
          <div className="space-y-3">
            {sortedTemplates.map((template) => (
              <TemplateCard
                key={template.id}
                template={template}
                isSelected={template.id === selectedId}
                onClick={() => onSelect(template)}
              />
            ))}
          </div>
        )}
      </ScrollArea>
    </div>
  );
}

// ============================================================================
// 模板卡片组件
// ============================================================================

interface TemplateCardProps {
  template: PromptTemplate;
  isSelected: boolean;
  onClick: () => void;
}

function TemplateCard({ template, isSelected, onClick }: TemplateCardProps) {
  const categoryConfig = CATEGORY_CONFIG[template.category];

  return (
    <button
      onClick={onClick}
      className={cn(
        'w-full text-left p-4 rounded-lg border transition-all',
        'hover:border-primary/50 hover:shadow-md',
        isSelected && 'border-primary bg-primary/5 shadow-md'
      )}
    >
      {/* 头部：名称和类别 */}
      <div className="flex items-start justify-between gap-3 mb-2">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <h4 className="font-semibold truncate">{template.name}</h4>
            {template.isBuiltin && (
              <Badge variant="secondary" className="shrink-0 text-xs">
                <Star className="h-3 w-3 mr-1" />
                内置
              </Badge>
            )}
          </div>
          <p className="text-sm text-muted-foreground mt-1 line-clamp-2">
            {template.description}
          </p>
        </div>
        
        <Badge 
          variant="outline" 
          className={cn('shrink-0', categoryConfig.color)}
        >
          {categoryConfig.emoji} {categoryConfig.label}
        </Badge>
      </div>

      {/* 标签 */}
      {template.tags && template.tags.length > 0 && (
        <div className="flex gap-1.5 flex-wrap mb-2">
          {template.tags.slice(0, 4).map((tag, index) => (
            <Badge key={index} variant="secondary" className="text-xs">
              {tag}
            </Badge>
          ))}
          {template.tags.length > 4 && (
            <Badge variant="secondary" className="text-xs">
              +{template.tags.length - 4}
            </Badge>
          )}
        </div>
      )}

      {/* 底部：统计信息 */}
      <div className="flex items-center gap-4 text-xs text-muted-foreground mt-3 pt-3 border-t">
        <div className="flex items-center gap-1">
          <TrendingUp className="h-3 w-3" />
          <span>使用 {template.usageCount || 0} 次</span>
        </div>
        {template.variables && template.variables.length > 0 && (
          <div className="flex items-center gap-1">
            <Sparkles className="h-3 w-3" />
            <span>{template.variables.length} 个变量</span>
          </div>
        )}
        {template.rating && (
          <div className="flex items-center gap-1">
            <Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
            <span>{template.rating.toFixed(1)}</span>
          </div>
        )}
      </div>
    </button>
  );
}

